package com.jewelry.crm.model.dao;

import static com.jewelry.crm.common.Common.logger;
import org.hibernate.SessionFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class HibernateUtil {

    //Session Factory
    private final static AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
    private final static SessionFactory sessionFactory = context.getBean("sessionFactory", SessionFactory.class);

    //HibernateValidator Factory
    private static ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    private static Validator validator = vf.getValidator();

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }

    public static Validator getValidator(){
        return validator;
    }

    public static Boolean validate(Object object, Validator validator) {
        logger.debug("Started Validation");
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
        if (!constraintViolations.isEmpty()){
            for (ConstraintViolation<Object> cv : constraintViolations) {
                logger.error(String.format("Got validation error! model property: [%s], got value: [%s], error message: [%s]",
                        cv.getPropertyPath(), cv.getInvalidValue(), cv.getMessage()));
            }
        } else logger.debug("No errors were found");
        return constraintViolations.isEmpty();
    }
}
